{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "fa483a6b-4705-48de-884b-13a38a9671bb",
   "metadata": {},
   "source": [
    "数据分析中的常见操作，在Pandas中，分组是指使用特定的条件将原数据划分为多个组，聚合：对每个分组中的数据执行某些操作（如聚合、转换等），最后将就是你的结果进行整合\n",
    "- 分组与聚合（）"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c5f3fea9-a5da-48fb-8921-ca6e5c49ebdc",
   "metadata": {},
   "source": [
    "## 【重要】在Pandas()中，可以通过【groupby()】将数据拆分成组\n",
    "- 分组聚合第一个步骤是将数据拆分成组，groupby()将数据集按照某些标准划分为若干组\n",
    "- groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=False, observed=False, **kwargs)\n",
    "- by: 用于确定分组的依据\n",
    "- axis: 表示分组的轴的方向，可以为0（表示按行）或为1（表示按列），默认为0值\n",
    "- level: 如果某个轴是一个MultiIndex对象（索引层结构），则会按特定几倍或多个级别分组\n",
    "- as_index: 表示聚合后的数据是否以组标签作为索引的DataFrame对象输出，接收布尔值，默认为True\n",
    "- sort: 表示是否对分组标签进行排序，接收布尔值，默认为True\n",
    "- group_keys:\n",
    "- squeeze:\n",
    "- observed:\n",
    "- **kwargs: "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "81f96a06-41c5-4c7d-a367-ead3295326c8",
   "metadata": {},
   "source": [
    "- 通过groupby()方法执行分组标签排序，会返回一个groupby对象，该对象实际上并没有进行任何计算，只是包含一些关于分组键（比如‘df_obj['key1']’）的中间数据而已。一般使用Series调用groupby()，返回的是SeriesGroupBy对象，而使用DataFrame调用groupby()返回的是DataFrame对象\n",
    "- 在进行分组时，可以通过groupbu()方法的by参数指定按什么标准分组，by参数可以接收的数据有多种形式，类型也不必相同，分组方式有4种：\n",
    "- "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "830b184a-ece0-42b9-bd6b-d5a6339de80e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Key</th>\n",
       "      <th>Data</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>C</td>\n",
       "      <td>2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>B</td>\n",
       "      <td>4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>C</td>\n",
       "      <td>6</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>A</td>\n",
       "      <td>8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>B</td>\n",
       "      <td>10</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>B</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>A</td>\n",
       "      <td>14</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>C</td>\n",
       "      <td>16</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>A</td>\n",
       "      <td>18</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "  Key  Data\n",
       "0   C     2\n",
       "1   B     4\n",
       "2   C     6\n",
       "3   A     8\n",
       "4   B    10\n",
       "5   B     1\n",
       "6   A    14\n",
       "7   C    16\n",
       "8   A    18"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "df = pd.DataFrame({'Key': ['C', 'B', 'C', 'A', 'B', 'B', 'A', 'C', 'A'],\n",
    "                  'Data': [2,4,6,8,10,1,14,16,18]})\n",
    "df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "ddc61cc3-62e1-467d-a9ef-5e0320a3e07b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<pandas.core.groupby.generic.DataFrameGroupBy object at 0x0000012F67ED0590>"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#调用groupby()时把列名Key传给by参数，代表将Key作为分组键，让df对象按照Key列进行分组\n",
    "df.groupby(by='Key')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "316e307c-e3ee-4fb5-ba73-bb69ca7493ca",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('A',   Key  Data\n",
      "3   A     8\n",
      "6   A    14\n",
      "8   A    18)\n",
      "('B',   Key  Data\n",
      "1   B     4\n",
      "4   B    10\n",
      "5   B     1)\n",
      "('C',   Key  Data\n",
      "0   C     2\n",
      "2   C     6\n",
      "7   C    16)\n"
     ]
    }
   ],
   "source": [
    "# 既然返回的是一个对象，那么要查看对象中的内容\n",
    "group_obj = df.groupby('Key')\n",
    "#遍历分组对象\n",
    "for i in group_obj:\n",
    "    print(i)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6a255038-2068-4790-a828-90ea7927a565",
   "metadata": {},
   "source": [
    "- 从输出的结果可以看出，DataFrame对象经过分组后得到了一个DataFrameGroupBy对象，该对象是一个可迭代的对象，只有当真正需要的时候在会执行计算\n",
    "- 如果要查看每个分组的具体内容，使用for 循环"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d8111594-938b-4f3b-b699-ea0a351ec9ba",
   "metadata": {},
   "source": [
    "### 2. 通过Series对象进行分组\n",
    "- 除此之外，还可以自定义Series对象，将其作为分组键，"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5974e954-f865-4a8f-95c5-732d3b975ec8",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "df = pd.DataFrame({'key1': ['A', 'A', 'B', 'B', 'A'],\n",
    "                  'key2': ['one', 'two', 'one', 'two', 'one'],\n",
    "                  'data1': [2,3,4,6,8],\n",
    "                  'data2': [3,5,6,3,7]})\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "db6d5566-c2ae-4d70-ab67-2e17668a2ef3",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0    a\n",
       "1    b\n",
       "2    c\n",
       "3    a\n",
       "4    b\n",
       "dtype: object"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 然后创建一个用于分组键的Series对象\n",
    "se = pd.Series(['a', 'b', 'c', 'a', 'b'])\n",
    "se"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "f499cc1f-23b0-484d-93ec-e60fd7a67d74",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('a',   Key  Data\n",
      "0   C     2\n",
      "3   A     8)\n",
      "('b',   Key  Data\n",
      "1   B     4\n",
      "4   B    10)\n",
      "('c',   Key  Data\n",
      "2   C     6)\n"
     ]
    }
   ],
   "source": [
    "#接着，调用groupby()把se对象传给by参数，把se对象作为分组键拆分df对象\n",
    "# 以得到一个分组对象，遍历该分组对象并查看每个分组的具体内容\n",
    "group_obj = df.groupby(by=se)\n",
    "for i in group_obj:\n",
    "    print(i)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "87048801-ab70-4ea8-9f33-1cb5d859c221",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('a',   Key  Data\n",
      "0   C     2\n",
      "1   B     4)\n",
      "('b',   Key  Data\n",
      "2   C     6)\n"
     ]
    }
   ],
   "source": [
    "#当Series长度与原数据的索引值长度不同时\n",
    "se = pd.Series(['a', 'a', 'b'])\n",
    "group_obj = df.groupby(se)    #将参数传递到groupby()函数中\n",
    "for i in group_obj:    #遍历\n",
    "    print(i)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a667d617-be34-4af8-9335-c99999bae4d9",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "81686d07-a6a8-4bdc-b2ce-b7f9133ab576",
   "metadata": {},
   "source": [
    "### 3.通过字典进行分组\n",
    "- 当用字典对DataFrame对性进行分组时，则需要确定轴的方向及字典的"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "ff27ab9f-b92a-430f-86be-28fed7cfd351",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>a</th>\n",
       "      <th>b</th>\n",
       "      <th>c</th>\n",
       "      <th>d</th>\n",
       "      <th>e</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1</td>\n",
       "      <td>6</td>\n",
       "      <td>11</td>\n",
       "      <td>5</td>\n",
       "      <td>10</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2</td>\n",
       "      <td>7</td>\n",
       "      <td>12</td>\n",
       "      <td>4</td>\n",
       "      <td>9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>3</td>\n",
       "      <td>8</td>\n",
       "      <td>13</td>\n",
       "      <td>3</td>\n",
       "      <td>8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>4</td>\n",
       "      <td>9</td>\n",
       "      <td>14</td>\n",
       "      <td>2</td>\n",
       "      <td>7</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>5</td>\n",
       "      <td>10</td>\n",
       "      <td>15</td>\n",
       "      <td>1</td>\n",
       "      <td>6</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   a   b   c  d   e\n",
       "0  1   6  11  5  10\n",
       "1  2   7  12  4   9\n",
       "2  3   8  13  3   8\n",
       "3  4   9  14  2   7\n",
       "4  5  10  15  1   6"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 通过字典进行分组\n",
    "import pandas as pd\n",
    "from pandas import DataFrame, Series\n",
    "num_df = DataFrame({'a': [1,2,3,4,5],\n",
    "                   'b': [6,7,8,9,10],\n",
    "                   'c': [11,12,13,14,15],\n",
    "                   'd': [5,4,3,2,1],\n",
    "                   'e': [10,9,8,7,6]})\n",
    "num_df"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "81d4beec-4523-441d-8f01-84585102ee17",
   "metadata": {},
   "source": [
    "然后创建一个表示分组规则的字典，其中字典的键为"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "6b335a34-49a4-49c5-9568-50dccc39ede4",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'a': '第一组', 'b': '第二组', 'c': '第一组', 'd': '第三组', 'e': '第二组'}"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 然后创建一个表示分组规则\n",
    "mapping = {'a': '第一组', 'b': '第二组','c': '第一组','d': '第三组','e': '第二组'}\n",
    "mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5fff16da-1d03-4def-918f-6a089826aa6b",
   "metadata": {},
   "outputs": [],
   "source": [
    "#接着调用groupby(),在该方法中传入刚刚创建的字典mapping, 将 mapping作为分组键拆分num_df对象\n",
    "#按字典分组\n",
    "by_column = num_df.groupby(mapping, axis=1)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "acc78148-2f44-47ad-8585-20fa3f48b05c",
   "metadata": {},
   "source": [
    "上述示例拆分num_df时，按照横轴的方式进行分组，将a列，c列是数据映射到第一组，将b列，e列是数据映射到第二组，将d列数据映射到第三组，从输出结果可以看出·"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "43dbd492-315b-4f1f-82ca-3ff1e40d19bb",
   "metadata": {},
   "source": [
    "### 4.通过函数进行分组"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1b2c4549-4235-40c1-b66f-94d1617fd8a6",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "num_df = DataFrame({'a': [1,2,3,4,5],\n",
    "                   'b': [6,7,8,9,10],\n",
    "                   'c': [5,4,3,2,1], index=['Sun': ]})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b279c16f-ece9-42b6-899b-c009659fb926",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "data = pd.DataFrame({'成绩': [90,83,84,75,92,93,95,85,95,64],\n",
    "                    '身高': [165,166,173,163,185,171,183,184,168,165],\n",
    "                    '排名': []})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3d1b2dde-bedf-4263-be29-2c1efb3910df",
   "metadata": {},
   "source": [
    "## 数据聚合"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "29d7e263-bd5a-4d70-b772-e3bb939d47f0",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>key1</th>\n",
       "      <th>key2</th>\n",
       "      <th>data1</th>\n",
       "      <th>data2</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>A</td>\n",
       "      <td>one</td>\n",
       "      <td>2</td>\n",
       "      <td>3.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>A</td>\n",
       "      <td>two</td>\n",
       "      <td>3</td>\n",
       "      <td>5.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>B</td>\n",
       "      <td>one</td>\n",
       "      <td>4</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>B</td>\n",
       "      <td>two</td>\n",
       "      <td>6</td>\n",
       "      <td>3.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>A</td>\n",
       "      <td>one</td>\n",
       "      <td>8</td>\n",
       "      <td>7.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "  key1 key2  data1  data2\n",
       "0    A  one      2    3.0\n",
       "1    A  two      3    5.0\n",
       "2    B  one      4    NaN\n",
       "3    B  two      6    3.0\n",
       "4    A  one      8    7.0"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "df = pd.DataFrame({'key1': ['A', 'A', 'B', 'B', 'A'],\n",
    "                    'key2': ['one', 'two', 'one', 'two', 'one'],\n",
    "                    'data1': [2, 3, 4, 6, 8],\n",
    "                    'data2': [3, 5, np.nan, 3, 7]})\n",
    "df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e3a65412-5b91-4e55-82cc-ca55f8a58c25",
   "metadata": {},
   "outputs": [],
   "source": [
    "df_group_mean = df.groupby('key1').mean()    #按key1进行分组，求每个分组的平均值\n",
    "df_group_mean    #如果此时不能对某些列进行分组操作，那么在此操作中，则不能使用全局操作进行分组"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "55271a20-0e13-4f35-8c0e-cdab4a0f1202",
   "metadata": {},
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "invalid syntax. Maybe you meant '==' or ':=' instead of '='? (2527235460.py, line 4)",
     "output_type": "error",
     "traceback": [
      "\u001b[1;36m  Cell \u001b[1;32mIn[17], line 4\u001b[1;36m\u001b[0m\n\u001b[1;33m    data_frame = DataFrame(np.arange(36).reshape((6, 6))), columns=list('abcdef')\u001b[0m\n\u001b[1;37m    ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m invalid syntax. Maybe you meant '==' or ':=' instead of '='?\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "from pandas import DataFrame, Series\n",
    "data_frame = DataFrame(np.arange(36).reshape((6, 6))), columns=list('abcdef')\n",
    "data_frame['key'] = Series(list['aaabbb'], name='key')\n",
    "data_frame['key'] = Series(list['testtest'], name='key')\n",
    "data_frame"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9197a7cb-0795-4727-ba61-0e83f928caab",
   "metadata": {},
   "outputs": [],
   "source": [
    "#按照c列进行分组\n",
    "data_group = data_frame.group('c')\n",
    "#输出a组的数据信息\n",
    "dict([x for x in data_group])['']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "6ba9f014-6370-4e96-9ea1-a144c7057000",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  key1 key2  data1  data2\n",
      "0    A  one      2    3.0\n",
      "1    A  two      3    5.0\n",
      "2    B  one      4    NaN\n",
      "3    B  two      6    3.0\n",
      "4    A  one      8    7.0\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>data1</th>\n",
       "      <th>data2</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>key1</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>A</th>\n",
       "      <td>4.333333</td>\n",
       "      <td>5.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>B</th>\n",
       "      <td>5.000000</td>\n",
       "      <td>3.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "         data1  data2\n",
       "key1                 \n",
       "A     4.333333    5.0\n",
       "B     5.000000    3.0"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "df = pd.DataFrame({'key1': ['A', 'A', 'B', 'B', 'A'],\n",
    "                    'key2': ['one', 'two', 'one', 'two', 'one'],\n",
    "                    'data1': [2, 3, 4, 6, 8],\n",
    "                    'data2': [3, 5, np.nan, 3, 7]})\n",
    "print(df)\n",
    "# 按key1 进行分组，并对数据列求平均值，需要忽略key2\n",
    "df_group_mean = df.groupby('key1').mean(numeric_only=True)\n",
    "df_group_mean"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "ca28521f-163b-4c84-80cd-e5225197ef9b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>key2</th>\n",
       "      <th>data1</th>\n",
       "      <th>data2</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>key1</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>A</th>\n",
       "      <td>one</td>\n",
       "      <td>4.333333</td>\n",
       "      <td>5.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>B</th>\n",
       "      <td>one</td>\n",
       "      <td>5.000000</td>\n",
       "      <td>3.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "     key2     data1  data2\n",
       "key1                      \n",
       "A     one  4.333333    5.0\n",
       "B     one  5.000000    3.0"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#对不同的列应用不同的参数\n",
    "df_grouped = df.groupby('key1').agg({'key2': 'first', 'data1': 'mean', 'data2': 'mean'})\n",
    "df_grouped"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "c92e5007-9c62-4a66-9aff-540c713338b3",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>a</th>\n",
       "      <th>b</th>\n",
       "      <th>c</th>\n",
       "      <th>d</th>\n",
       "      <th>e</th>\n",
       "      <th>f</th>\n",
       "      <th>key</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>2</td>\n",
       "      <td>3</td>\n",
       "      <td>4</td>\n",
       "      <td>5</td>\n",
       "      <td>a</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>6</td>\n",
       "      <td>7</td>\n",
       "      <td>8</td>\n",
       "      <td>9</td>\n",
       "      <td>10</td>\n",
       "      <td>11</td>\n",
       "      <td>a</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>12</td>\n",
       "      <td>13</td>\n",
       "      <td>14</td>\n",
       "      <td>15</td>\n",
       "      <td>16</td>\n",
       "      <td>17</td>\n",
       "      <td>a</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>18</td>\n",
       "      <td>19</td>\n",
       "      <td>20</td>\n",
       "      <td>21</td>\n",
       "      <td>22</td>\n",
       "      <td>23</td>\n",
       "      <td>b</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>24</td>\n",
       "      <td>25</td>\n",
       "      <td>26</td>\n",
       "      <td>27</td>\n",
       "      <td>28</td>\n",
       "      <td>29</td>\n",
       "      <td>b</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>30</td>\n",
       "      <td>31</td>\n",
       "      <td>32</td>\n",
       "      <td>33</td>\n",
       "      <td>34</td>\n",
       "      <td>35</td>\n",
       "      <td>b</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "    a   b   c   d   e   f key\n",
       "0   0   1   2   3   4   5   a\n",
       "1   6   7   8   9  10  11   a\n",
       "2  12  13  14  15  16  17   a\n",
       "3  18  19  20  21  22  23   b\n",
       "4  24  25  26  27  28  29   b\n",
       "5  30  31  32  33  34  35   b"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "#创建一个 6x6的DataFrame, 并\n",
    "data_frame = pd.DataFrame(np.arange(36).reshape((6,6)), columns=list('abcdef'))\n",
    "\n",
    "#正确创建表并添加 'key' 列\n",
    "data_frame['key'] = pd.Series(list('aaabbb'), name='key')\n",
    "\n",
    "#打印 DataFrame 以检验结果\n",
    "data_frame"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "326ee8bb-7a49-4f29-84ea-5a82664472cd",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>a</th>\n",
       "      <th>b</th>\n",
       "      <th>c</th>\n",
       "      <th>d</th>\n",
       "      <th>e</th>\n",
       "      <th>f</th>\n",
       "      <th>key</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>2</td>\n",
       "      <td>3</td>\n",
       "      <td>4</td>\n",
       "      <td>5</td>\n",
       "      <td>a</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>6</td>\n",
       "      <td>7</td>\n",
       "      <td>8</td>\n",
       "      <td>9</td>\n",
       "      <td>10</td>\n",
       "      <td>11</td>\n",
       "      <td>a</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>12</td>\n",
       "      <td>13</td>\n",
       "      <td>14</td>\n",
       "      <td>15</td>\n",
       "      <td>16</td>\n",
       "      <td>17</td>\n",
       "      <td>a</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "    a   b   c   d   e   f key\n",
       "0   0   1   2   3   4   5   a\n",
       "1   6   7   8   9  10  11   a\n",
       "2  12  13  14  15  16  17   a"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 按key列进行分组\n",
    "data_group = data_frame.groupby('key')    #输出a组数据信息\n",
    "dict([x for x in data_group])['a']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "92ccf435-5af2-4270-baa8-dc75b2dd3bf6",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>a</th>\n",
       "      <th>b</th>\n",
       "      <th>c</th>\n",
       "      <th>d</th>\n",
       "      <th>e</th>\n",
       "      <th>f</th>\n",
       "      <th>key</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>18</td>\n",
       "      <td>19</td>\n",
       "      <td>20</td>\n",
       "      <td>21</td>\n",
       "      <td>22</td>\n",
       "      <td>23</td>\n",
       "      <td>b</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>24</td>\n",
       "      <td>25</td>\n",
       "      <td>26</td>\n",
       "      <td>27</td>\n",
       "      <td>28</td>\n",
       "      <td>29</td>\n",
       "      <td>b</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>30</td>\n",
       "      <td>31</td>\n",
       "      <td>32</td>\n",
       "      <td>33</td>\n",
       "      <td>34</td>\n",
       "      <td>35</td>\n",
       "      <td>b</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "    a   b   c   d   e   f key\n",
       "3  18  19  20  21  22  23   b\n",
       "4  24  25  26  27  28  29   b\n",
       "5  30  31  32  33  34  35   b"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 输出b组数据信息\n",
    "data_group = data_frame.groupby('key')    #输出a组数据信息\n",
    "dict([x for x in data_group])['b']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "3338da6c-12ce-452f-926c-5f40656e6a6f",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Windows\\Temp\\ipykernel_24764\\1032060970.py:2: FutureWarning: The provided callable <built-in function sum> is currently using DataFrameGroupBy.sum. In a future version of pandas, the provided callable will be used directly. To keep current behavior pass the string \"sum\" instead.\n",
      "  data_group.agg(sum)\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>a</th>\n",
       "      <th>b</th>\n",
       "      <th>c</th>\n",
       "      <th>d</th>\n",
       "      <th>e</th>\n",
       "      <th>f</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>key</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>a</th>\n",
       "      <td>18</td>\n",
       "      <td>21</td>\n",
       "      <td>24</td>\n",
       "      <td>27</td>\n",
       "      <td>30</td>\n",
       "      <td>33</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>b</th>\n",
       "      <td>72</td>\n",
       "      <td>75</td>\n",
       "      <td>78</td>\n",
       "      <td>81</td>\n",
       "      <td>84</td>\n",
       "      <td>87</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "      a   b   c   d   e   f\n",
       "key                        \n",
       "a    18  21  24  27  30  33\n",
       "b    72  75  78  81  84  87"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#求每个分组的和\n",
    "data_group.agg(sum)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "65e438d6-f44b-4782-b298-f14d0f3cb74c",
   "metadata": {},
   "outputs": [],
   "source": [
    "#自定义函数求极差值\n",
    "def range_data_group(arr):\n",
    "    return arr.max() - arr.min()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "55d93c2c-b15d-4172-a9fc-a72fba18240c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>a</th>\n",
       "      <th>b</th>\n",
       "      <th>c</th>\n",
       "      <th>d</th>\n",
       "      <th>e</th>\n",
       "      <th>f</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>key</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>a</th>\n",
       "      <td>12</td>\n",
       "      <td>12</td>\n",
       "      <td>12</td>\n",
       "      <td>12</td>\n",
       "      <td>12</td>\n",
       "      <td>12</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>b</th>\n",
       "      <td>12</td>\n",
       "      <td>12</td>\n",
       "      <td>12</td>\n",
       "      <td>12</td>\n",
       "      <td>12</td>\n",
       "      <td>12</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "      a   b   c   d   e   f\n",
       "key                        \n",
       "a    12  12  12  12  12  12\n",
       "b    12  12  12  12  12  12"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data_group.agg(range_data_group)    #使用自定义函数聚合分组数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "22db0a63-90f7-4d12-bce0-e81f468e1510",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Windows\\Temp\\ipykernel_24764\\2609447362.py:2: FutureWarning: The provided callable <built-in function sum> is currently using SeriesGroupBy.sum. In a future version of pandas, the provided callable will be used directly. To keep current behavior pass the string \"sum\" instead.\n",
      "  data_group.agg([range_data_group, sum])\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead tr th {\n",
       "        text-align: left;\n",
       "    }\n",
       "\n",
       "    .dataframe thead tr:last-of-type th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr>\n",
       "      <th></th>\n",
       "      <th colspan=\"2\" halign=\"left\">a</th>\n",
       "      <th colspan=\"2\" halign=\"left\">b</th>\n",
       "      <th colspan=\"2\" halign=\"left\">c</th>\n",
       "      <th colspan=\"2\" halign=\"left\">d</th>\n",
       "      <th colspan=\"2\" halign=\"left\">e</th>\n",
       "      <th colspan=\"2\" halign=\"left\">f</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th></th>\n",
       "      <th>range_data_group</th>\n",
       "      <th>sum</th>\n",
       "      <th>range_data_group</th>\n",
       "      <th>sum</th>\n",
       "      <th>range_data_group</th>\n",
       "      <th>sum</th>\n",
       "      <th>range_data_group</th>\n",
       "      <th>sum</th>\n",
       "      <th>range_data_group</th>\n",
       "      <th>sum</th>\n",
       "      <th>range_data_group</th>\n",
       "      <th>sum</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>key</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>a</th>\n",
       "      <td>12</td>\n",
       "      <td>18</td>\n",
       "      <td>12</td>\n",
       "      <td>21</td>\n",
       "      <td>12</td>\n",
       "      <td>24</td>\n",
       "      <td>12</td>\n",
       "      <td>27</td>\n",
       "      <td>12</td>\n",
       "      <td>30</td>\n",
       "      <td>12</td>\n",
       "      <td>33</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>b</th>\n",
       "      <td>12</td>\n",
       "      <td>72</td>\n",
       "      <td>12</td>\n",
       "      <td>75</td>\n",
       "      <td>12</td>\n",
       "      <td>78</td>\n",
       "      <td>12</td>\n",
       "      <td>81</td>\n",
       "      <td>12</td>\n",
       "      <td>84</td>\n",
       "      <td>12</td>\n",
       "      <td>87</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                   a                    b                    c  ...   d                e                    f    \n",
       "    range_data_group sum range_data_group sum range_data_group  ... sum range_data_group sum range_data_group sum\n",
       "key                                                             ...                                              \n",
       "a                 12  18               12  21               12  ...  27               12  30               12  33\n",
       "b                 12  72               12  75               12  ...  81               12  84               12  87\n",
       "\n",
       "[2 rows x 12 columns]"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#对一列数据采用两种函数聚合\n",
    "data_group.agg([range_data_group, sum])\n",
    "#对象.agg([自定义函数求极差值, sum函数求和])\n",
    "#这样他就自动对不同的分组a组和b组，分别求极差值 和 求和"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "f04f7966-ab2e-4341-aaa4-e06a2377e98e",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Windows\\Temp\\ipykernel_24764\\3847496112.py:1: FutureWarning: The provided callable <built-in function sum> is currently using SeriesGroupBy.sum. In a future version of pandas, the provided callable will be used directly. To keep current behavior pass the string \"sum\" instead.\n",
      "  data_group.agg([('极差', range_data_group), ('和', sum)])\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead tr th {\n",
       "        text-align: left;\n",
       "    }\n",
       "\n",
       "    .dataframe thead tr:last-of-type th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr>\n",
       "      <th></th>\n",
       "      <th colspan=\"2\" halign=\"left\">a</th>\n",
       "      <th colspan=\"2\" halign=\"left\">b</th>\n",
       "      <th colspan=\"2\" halign=\"left\">c</th>\n",
       "      <th colspan=\"2\" halign=\"left\">d</th>\n",
       "      <th colspan=\"2\" halign=\"left\">e</th>\n",
       "      <th colspan=\"2\" halign=\"left\">f</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th></th>\n",
       "      <th>极差</th>\n",
       "      <th>和</th>\n",
       "      <th>极差</th>\n",
       "      <th>和</th>\n",
       "      <th>极差</th>\n",
       "      <th>和</th>\n",
       "      <th>极差</th>\n",
       "      <th>和</th>\n",
       "      <th>极差</th>\n",
       "      <th>和</th>\n",
       "      <th>极差</th>\n",
       "      <th>和</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>key</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>a</th>\n",
       "      <td>12</td>\n",
       "      <td>18</td>\n",
       "      <td>12</td>\n",
       "      <td>21</td>\n",
       "      <td>12</td>\n",
       "      <td>24</td>\n",
       "      <td>12</td>\n",
       "      <td>27</td>\n",
       "      <td>12</td>\n",
       "      <td>30</td>\n",
       "      <td>12</td>\n",
       "      <td>33</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>b</th>\n",
       "      <td>12</td>\n",
       "      <td>72</td>\n",
       "      <td>12</td>\n",
       "      <td>75</td>\n",
       "      <td>12</td>\n",
       "      <td>78</td>\n",
       "      <td>12</td>\n",
       "      <td>81</td>\n",
       "      <td>12</td>\n",
       "      <td>84</td>\n",
       "      <td>12</td>\n",
       "      <td>87</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "      a       b       c       d       e       f    \n",
       "     极差   和  极差   和  极差   和  极差   和  极差   和  极差   和\n",
       "key                                                \n",
       "a    12  18  12  21  12  24  12  27  12  30  12  33\n",
       "b    12  72  12  75  12  78  12  81  12  84  12  87"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data_group.agg([('极差', range_data_group), ('和', sum)])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "3be098b8-9f17-487a-b715-4ee1710a6e63",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>a</th>\n",
       "      <th>b</th>\n",
       "      <th>c</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>key</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>a</th>\n",
       "      <td>18</td>\n",
       "      <td>7.0</td>\n",
       "      <td>12</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>b</th>\n",
       "      <td>72</td>\n",
       "      <td>25.0</td>\n",
       "      <td>12</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "      a     b   c\n",
       "key              \n",
       "a    18   7.0  12\n",
       "b    72  25.0  12"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#使用不同的函数聚合分组数据\n",
    "# 'a': 'sum' 相当于a 列使用sum求和\n",
    "# 'b': 'mean' 相当于b 列使用mean求均值\n",
    "# 'c': range_data_group 相当于c列使用刚才自定义的函数求极差值\n",
    "# agg() 强大的地方在于，直接传入函数名（注意大小写），即可底层进行计算\n",
    "data_group.agg({'a': 'sum', 'b': 'mean', 'c': range_data_group})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "264ef9ed-ead9-4257-bf60-6fe2daf51470",
   "metadata": {},
   "source": [
    "### 分级运算\n",
    "#### 数据转换"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "269ec6bf-b476-41eb-876c-1cc94c3553d8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "    a   b   c   d   e key\n",
      "0   0   1   2   3   4   A\n",
      "1   1   2   3   4   5   A\n",
      "2   6   7   8   9  10   B\n",
      "3  10  11  12  13  14   B\n",
      "4   3   4   4   5   3   B\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>a</th>\n",
       "      <th>b</th>\n",
       "      <th>c</th>\n",
       "      <th>d</th>\n",
       "      <th>e</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>0.500000</td>\n",
       "      <td>1.500000</td>\n",
       "      <td>2.5</td>\n",
       "      <td>3.5</td>\n",
       "      <td>4.5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>0.500000</td>\n",
       "      <td>1.500000</td>\n",
       "      <td>2.5</td>\n",
       "      <td>3.5</td>\n",
       "      <td>4.5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>6.333333</td>\n",
       "      <td>7.333333</td>\n",
       "      <td>8.0</td>\n",
       "      <td>9.0</td>\n",
       "      <td>9.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>6.333333</td>\n",
       "      <td>7.333333</td>\n",
       "      <td>8.0</td>\n",
       "      <td>9.0</td>\n",
       "      <td>9.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>6.333333</td>\n",
       "      <td>7.333333</td>\n",
       "      <td>8.0</td>\n",
       "      <td>9.0</td>\n",
       "      <td>9.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "          a         b    c    d    e\n",
       "0  0.500000  1.500000  2.5  3.5  4.5\n",
       "1  0.500000  1.500000  2.5  3.5  4.5\n",
       "2  6.333333  7.333333  8.0  9.0  9.0\n",
       "3  6.333333  7.333333  8.0  9.0  9.0\n",
       "4  6.333333  7.333333  8.0  9.0  9.0"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "df = pd.DataFrame({'a': [0,1,6,10,3],\n",
    "                  'b': [1,2,7,11,4],\n",
    "                  'c': [2,3,8,12,4],\n",
    "                  'd': [3,4,9,13,5],\n",
    "                  'e': [4,5,10,14,3],\n",
    "                  'key': ['A', 'A', 'B', 'B', 'B']})\n",
    "print(df)\n",
    "\n",
    "data_group = df.groupby('key').transform('mean')\n",
    "data_group"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7a61ff5d-0f1e-41fa-a3e8-170ccac056db",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "e34242e0-39ce-4850-9058-7c3146ce3767",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   A  B  C   D\n",
      "0  2  4  9   3\n",
      "1  3  3  7   4\n",
      "2  3  3  0   8\n",
      "3  4  6  7   6\n",
      "4  2  6  8  10\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>A</th>\n",
       "      <th>B</th>\n",
       "      <th>C</th>\n",
       "      <th>D</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>2.5</td>\n",
       "      <td>3.5</td>\n",
       "      <td>8.0</td>\n",
       "      <td>3.5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2.5</td>\n",
       "      <td>3.5</td>\n",
       "      <td>8.0</td>\n",
       "      <td>3.5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>3.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>8.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>3.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>8.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>3.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>8.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "     A    B    C    D\n",
       "0  2.5  3.5  8.0  3.5\n",
       "1  2.5  3.5  8.0  3.5\n",
       "2  3.0  5.0  5.0  8.0\n",
       "3  3.0  5.0  5.0  8.0\n",
       "4  3.0  5.0  5.0  8.0"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "df = pd.DataFrame({'A': [2,3,3,4,2],\n",
    "                  'B': [4,3,3,6,6],\n",
    "                  'C': [9,7,0,7,8],\n",
    "                  'D': [3,4,8,6,10]})\n",
    "print(df)\n",
    "\n",
    "#以 key 为分组依据，对df 对象进行分组\n",
    "key=['one', 'one', 'two', 'two', 'two']\n",
    "df.groupby(key).transform('mean')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7f1ece35-d047-4dd6-badd-6da9b02dbdc0",
   "metadata": {},
   "source": [
    "#### 数据应用"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "d78e3d96-e2fa-42a0-8c3e-0a7fe244e91c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   data1  data2  data3 key\n",
      "0     80     41     30   b\n",
      "1     23     87     78   a\n",
      "2     25     58     23   a\n",
      "3     63     68     66   b\n",
      "4     94     72     16   b\n",
      "5     92     89     59   a\n",
      "6     99     60     20   b\n",
      "7     92     42     23   a\n",
      "8     82     53     24   a\n",
      "9     99     65     40   a\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>data1</th>\n",
       "      <th>data2</th>\n",
       "      <th>data3</th>\n",
       "      <th>key</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>23</td>\n",
       "      <td>87</td>\n",
       "      <td>78</td>\n",
       "      <td>a</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>25</td>\n",
       "      <td>58</td>\n",
       "      <td>23</td>\n",
       "      <td>a</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>92</td>\n",
       "      <td>89</td>\n",
       "      <td>59</td>\n",
       "      <td>a</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>92</td>\n",
       "      <td>42</td>\n",
       "      <td>23</td>\n",
       "      <td>a</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>82</td>\n",
       "      <td>53</td>\n",
       "      <td>24</td>\n",
       "      <td>a</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>99</td>\n",
       "      <td>65</td>\n",
       "      <td>40</td>\n",
       "      <td>a</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   data1  data2  data3 key\n",
       "1     23     87     78   a\n",
       "2     25     58     23   a\n",
       "5     92     89     59   a\n",
       "7     92     42     23   a\n",
       "8     82     53     24   a\n",
       "9     99     65     40   a"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from pandas import DataFrame, Series\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "data_frame = DataFrame({'data1': [80,23,25,63,94,92,99,92,82,99],\n",
    "                       'data2': [41,87,58,68,72,89,60,42,53,65],\n",
    "                       'data3': [30,78,23,66,16,59,20,23,24,40],\n",
    "                       'key': list('baabbabaaa')})\n",
    "print(data_frame)\n",
    "\n",
    "#对数据进行分组\n",
    "data_by_group = data_frame.groupby('key')\n",
    "#打印分组数据\n",
    "dict([x for x in data_by_group])['a']"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "32803212-73f4-4edd-8387-d1fbb9ae5515",
   "metadata": {},
   "source": [
    "### 案例--奥运会参赛人员信息的分组与聚合"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "71c72e60-4a78-4fbb-aad1-9f9f79ec0a71",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "       姓名 性别 出生年份（年）  年龄（岁）  身高(cm)  体重(kg)      项目     省份\n",
      "0     陈楠   女   1983年     35     197      90      篮球    山东省\n",
      "1    白发全   男   1986年     32     175      64    铁人三项    云南省\n",
      "2    陈晓佳   女   1988年     30     180      70      篮球    江苏省\n",
      "3     陈倩   女   1987年     31     163      54  女子现代五项  江苏省  \n",
      "4    曹忠荣   男   1981年     37     180      73  男子现代五项    上海市\n",
      "..    ... ..     ...    ...     ...     ...     ...    ...\n",
      "174  赵芸蕾   女   1986年     32     173      62     羽毛球    湖北省\n",
      "175   周琦   男   1996年     22     217      95      篮球   河南省 \n",
      "176  翟晓川   男   1993年     25     204     100      篮球   河北省 \n",
      "177  赵继伟   男   1995年     23     185      77      篮球    辽宁省\n",
      "178  邹雨宸   男   1996年     22     208     108      篮球    辽宁省\n",
      "\n",
      "[179 rows x 8 columns]\n",
      "        姓名 性别 出生年份（年）  年龄（岁）  身高(cm)  体重(kg)  项目        省份\n",
      "0      陈楠   女   1983年     35     197      90  篮球       山东省\n",
      "2     陈晓佳   女   1988年     30     180      70  篮球       江苏省\n",
      "16   丁彦雨航   男   1993年     25     200      91  篮球  新疆维吾尔自治区\n",
      "23     高颂   女   1992年     26     191      85  篮球    黑龙江省  \n",
      "28    郭艾伦   男   1993年     25     192      85  篮球       辽宁省\n",
      "35    黄红枇   女   1989年     29     195      80  篮球   广西壮族自治区\n",
      "42    黄思静   女   1996年     22     192      80  篮球       广东省\n",
      "48    李慕豪   男   1992年     26     225     111  篮球      贵州贵阳\n",
      "54    李珊珊   女   1987年     31     177      70  篮球     江苏省  \n",
      "73     露雯   女   1990年     28     191      78  篮球    内蒙古自治区\n",
      "101   孙梦然   女   1992年     26     197      77  篮球       天津市\n",
      "102   孙梦昕   女   1993年     25     190      77  篮球     山东省  \n",
      "106    睢冉   男   1992年     26     192      95  篮球       山西省\n",
      "116    吴迪   女   1990年     28     186      72  篮球       天津市\n",
      "124   王哲林   男   1994年     24     214     110  篮球      福建省 \n",
      "155   易建联   男   1987年     31     213     113  篮球       广东省\n",
      "161    周鹏   男   1989年     29     206      90  篮球       辽宁省\n",
      "175    周琦   男   1996年     22     217      95  篮球      河南省 \n",
      "176   翟晓川   男   1993年     25     204     100  篮球      河北省 \n",
      "177   赵继伟   男   1995年     23     185      77  篮球       辽宁省\n",
      "178   邹雨宸   男   1996年     22     208     108  篮球       辽宁省\n",
      "        年龄（岁）      身高(cm)     体重(kg)\n",
      "性别                                  \n",
      "女   28.000000  189.600000  77.900000\n",
      "男   25.272727  205.090909  97.727273\n"
     ]
    }
   ],
   "source": [
    "# coding:UTF-8\n",
    "import pandas as pd\n",
    "#读取奥林匹克参赛人员信息表\n",
    "file_path = open('./data/运动员信息表.csv')\n",
    "df = pd.read_csv(file_path)\n",
    "print(df)\n",
    "\n",
    "#按项目一列进行分组\n",
    "data_group = df.groupby('项目')\n",
    "#输出篮球分组的信息\n",
    "df_basketball = dict([x for x in data_group])['篮球']\n",
    "print(df_basketball)\n",
    "\n",
    "#按性别一列进行分组， 并使用聚合方法\n",
    "#只选择数值型列进行均值计算\n",
    "numeric_columns = ['年龄（岁）', '身高(cm)', '体重(kg)']\n",
    "groupby_sex = df_basketball.groupby('性别')[numeric_columns].mean()\n",
    "print(groupby_sex)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "d5130815-c605-4bd1-8d5b-689592b3cc6c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "        姓名 性别 出生年份（年）  年龄（岁）  身高(cm)  体重(kg)  项目        省份  年龄（岁）_mean  身高(cm)_mean  体重(kg)_mean\n",
      "0      陈楠   女   1983年     35     197      90  篮球       山东省   28.000000   189.600000    77.900000\n",
      "2     陈晓佳   女   1988年     30     180      70  篮球       江苏省   28.000000   189.600000    77.900000\n",
      "16   丁彦雨航   男   1993年     25     200      91  篮球  新疆维吾尔自治区   25.272727   205.090909    97.727273\n",
      "23     高颂   女   1992年     26     191      85  篮球    黑龙江省     28.000000   189.600000    77.900000\n",
      "28    郭艾伦   男   1993年     25     192      85  篮球       辽宁省   25.272727   205.090909    97.727273\n",
      "35    黄红枇   女   1989年     29     195      80  篮球   广西壮族自治区   28.000000   189.600000    77.900000\n",
      "42    黄思静   女   1996年     22     192      80  篮球       广东省   28.000000   189.600000    77.900000\n",
      "48    李慕豪   男   1992年     26     225     111  篮球      贵州贵阳   25.272727   205.090909    97.727273\n",
      "54    李珊珊   女   1987年     31     177      70  篮球     江苏省     28.000000   189.600000    77.900000\n",
      "73     露雯   女   1990年     28     191      78  篮球    内蒙古自治区   28.000000   189.600000    77.900000\n",
      "101   孙梦然   女   1992年     26     197      77  篮球       天津市   28.000000   189.600000    77.900000\n",
      "102   孙梦昕   女   1993年     25     190      77  篮球     山东省     28.000000   189.600000    77.900000\n",
      "106    睢冉   男   1992年     26     192      95  篮球       山西省   25.272727   205.090909    97.727273\n",
      "116    吴迪   女   1990年     28     186      72  篮球       天津市   28.000000   189.600000    77.900000\n",
      "124   王哲林   男   1994年     24     214     110  篮球      福建省    25.272727   205.090909    97.727273\n",
      "155   易建联   男   1987年     31     213     113  篮球       广东省   25.272727   205.090909    97.727273\n",
      "161    周鹏   男   1989年     29     206      90  篮球       辽宁省   25.272727   205.090909    97.727273\n",
      "175    周琦   男   1996年     22     217      95  篮球      河南省    25.272727   205.090909    97.727273\n",
      "176   翟晓川   男   1993年     25     204     100  篮球      河北省    25.272727   205.090909    97.727273\n",
      "177   赵继伟   男   1995年     23     185      77  篮球       辽宁省   25.272727   205.090909    97.727273\n",
      "178   邹雨宸   男   1996年     22     208     108  篮球       辽宁省   25.272727   205.090909    97.727273\n"
     ]
    }
   ],
   "source": [
    "#使用transform 方法将数据进行聚合，并利用其特性将平均值进行分组\n",
    "info = df_basketball.groupby('性别')[numeric_columns].transform('mean')\n",
    "#将info添加到原始的篮球分组 DataFrame\n",
    "df_basketball_with_mean = df_basketball.copy()\n",
    "for col in numeric_columns:\n",
    "    df_basketball_with_mean[f'{col}_mean'] = info[col]\n",
    "\n",
    "print(df_basketball_with_mean)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "1da8c7d6-5705-4329-8e4c-8ce45023659c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>姓名</th>\n",
       "      <th>性别</th>\n",
       "      <th>出生年份（年）</th>\n",
       "      <th>年龄（岁）</th>\n",
       "      <th>身高(cm)</th>\n",
       "      <th>体重(kg)</th>\n",
       "      <th>项目</th>\n",
       "      <th>省份</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>16</th>\n",
       "      <td>丁彦雨航</td>\n",
       "      <td>男</td>\n",
       "      <td>1993年</td>\n",
       "      <td>25</td>\n",
       "      <td>200</td>\n",
       "      <td>91</td>\n",
       "      <td>篮球</td>\n",
       "      <td>新疆维吾尔自治区</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>28</th>\n",
       "      <td>郭艾伦</td>\n",
       "      <td>男</td>\n",
       "      <td>1993年</td>\n",
       "      <td>25</td>\n",
       "      <td>192</td>\n",
       "      <td>85</td>\n",
       "      <td>篮球</td>\n",
       "      <td>辽宁省</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>48</th>\n",
       "      <td>李慕豪</td>\n",
       "      <td>男</td>\n",
       "      <td>1992年</td>\n",
       "      <td>26</td>\n",
       "      <td>225</td>\n",
       "      <td>111</td>\n",
       "      <td>篮球</td>\n",
       "      <td>贵州贵阳</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>106</th>\n",
       "      <td>睢冉</td>\n",
       "      <td>男</td>\n",
       "      <td>1992年</td>\n",
       "      <td>26</td>\n",
       "      <td>192</td>\n",
       "      <td>95</td>\n",
       "      <td>篮球</td>\n",
       "      <td>山西省</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>124</th>\n",
       "      <td>王哲林</td>\n",
       "      <td>男</td>\n",
       "      <td>1994年</td>\n",
       "      <td>24</td>\n",
       "      <td>214</td>\n",
       "      <td>110</td>\n",
       "      <td>篮球</td>\n",
       "      <td>福建省</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>155</th>\n",
       "      <td>易建联</td>\n",
       "      <td>男</td>\n",
       "      <td>1987年</td>\n",
       "      <td>31</td>\n",
       "      <td>213</td>\n",
       "      <td>113</td>\n",
       "      <td>篮球</td>\n",
       "      <td>广东省</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>161</th>\n",
       "      <td>周鹏</td>\n",
       "      <td>男</td>\n",
       "      <td>1989年</td>\n",
       "      <td>29</td>\n",
       "      <td>206</td>\n",
       "      <td>90</td>\n",
       "      <td>篮球</td>\n",
       "      <td>辽宁省</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>175</th>\n",
       "      <td>周琦</td>\n",
       "      <td>男</td>\n",
       "      <td>1996年</td>\n",
       "      <td>22</td>\n",
       "      <td>217</td>\n",
       "      <td>95</td>\n",
       "      <td>篮球</td>\n",
       "      <td>河南省</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>176</th>\n",
       "      <td>翟晓川</td>\n",
       "      <td>男</td>\n",
       "      <td>1993年</td>\n",
       "      <td>25</td>\n",
       "      <td>204</td>\n",
       "      <td>100</td>\n",
       "      <td>篮球</td>\n",
       "      <td>河北省</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>177</th>\n",
       "      <td>赵继伟</td>\n",
       "      <td>男</td>\n",
       "      <td>1995年</td>\n",
       "      <td>23</td>\n",
       "      <td>185</td>\n",
       "      <td>77</td>\n",
       "      <td>篮球</td>\n",
       "      <td>辽宁省</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>178</th>\n",
       "      <td>邹雨宸</td>\n",
       "      <td>男</td>\n",
       "      <td>1996年</td>\n",
       "      <td>22</td>\n",
       "      <td>208</td>\n",
       "      <td>108</td>\n",
       "      <td>篮球</td>\n",
       "      <td>辽宁省</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        姓名 性别 出生年份（年）  年龄（岁）  身高(cm)  体重(kg)  项目        省份\n",
       "16   丁彦雨航   男   1993年     25     200      91  篮球  新疆维吾尔自治区\n",
       "28    郭艾伦   男   1993年     25     192      85  篮球       辽宁省\n",
       "48    李慕豪   男   1992年     26     225     111  篮球      贵州贵阳\n",
       "106    睢冉   男   1992年     26     192      95  篮球       山西省\n",
       "124   王哲林   男   1994年     24     214     110  篮球      福建省 \n",
       "155   易建联   男   1987年     31     213     113  篮球       广东省\n",
       "161    周鹏   男   1989年     29     206      90  篮球       辽宁省\n",
       "175    周琦   男   1996年     22     217      95  篮球      河南省 \n",
       "176   翟晓川   男   1993年     25     204     100  篮球      河北省 \n",
       "177   赵继伟   男   1995年     23     185      77  篮球       辽宁省\n",
       "178   邹雨宸   男   1996年     22     208     108  篮球       辽宁省"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#查看男篮运动员的分组\n",
    "basketball_male = df_basketball[df_basketball['性别'] == '男']\n",
    "basketball_male"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "4a960a7b-f724-4ea2-a7b1-4ceee6bb2104",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "年龄（岁）      9\n",
       "身高(cm)    40\n",
       "体重(kg)    36\n",
       "dtype: int64"
      ]
     },
     "execution_count": 35,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 求年龄、身高、体重这三组数据的极差值\n",
    "basketball_male.agg({'年龄（岁）': range_data_group, '身高(cm)': range_data_group, '体重(kg)': range_data_group})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "28102568-8303-44e4-8fa3-df0b58a59c4d",
   "metadata": {},
   "outputs": [],
   "source": [
    "#统计男篮运动员的体脂指数\n",
    "#在 df_basketball"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
